package com.whz.work.ex01;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * @ClassName Response
 * @Description TODO
 * @Author hong-zhi
 * @Date 2021/5/27 18:41
 * @Version 1.0
 */
@Slf4j
public class Response {
    private static final int BUFFER_SIZE = 1024;
    Request request;
    OutputStream output;

    public Response(OutputStream output) {
        this.output = output;
    }

    public void setRequest(Request request) {
        this.request = request;
    }
    public void sendStaticResource() throws IOException {
        File file = new File(HttpServer.WEB_ROOT, request.getUri());
        String result = null;
        if (file.exists()) {
            StringBuilder sb = new StringBuilder();
            try {
                BufferedReader br =new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                br.lines().forEach(sb::append);
                log.info("读取到文件中的内容: {}", sb);
                // 响应文件内容
                result = "HTTP/1.1 200 ok\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: "+ sb.length() +"\r\n" +
                        "\r\n" +
                        "<html><head><title>输出所查询的文件内容</title></head>" +
                        "<body><span>"+ sb +"</span></body>" +
                        "<html>";
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            // file not found
            result = "HTTP/1.1 404 File Not Found\r\n" +
                    "Content-Type: text/html\r\n" +
                    "Content-Length: 23\r\n" +
                    "\r\n" +
                    "<h1>File Not Found</h1>";

        }

        output.write(result.getBytes(Charset.defaultCharset()));
        output.flush();
    }
}
